<template>
  <div class="addMaintainPlan zy-content">
    <div class="title">
      <span>{{ !editId ? '新增精度检测计划' : '编辑精度检测计划'}}</span>
      <div class="back" @click="back">返回上一级</div>
      <Steps :current="current" class="steps">
        <Step title="选择检测对象"></Step>
        <Step title="添加检测内容"></Step>
        <Step title="创建检测时间"></Step>
      </Steps>
    </div>
    <!-- 第一步 -->
    <div class="searchBox" v-if="current === 0">
      <Form class="search-form"
            ref="stepOneValidate"
            :rules="stepOneRuleValidate"
            :model="formInline">
        <div class="labelTop">
          <FormItem label="检测计划" class="item" prop="planName">
            <Input
                    type="text"
                    v-model="formInline.planName"
                    :placeholder="`${$t('common.inputInfo')}`"
                    clearable
                    class="inputBorder"
                    :maxlength="100"
            ></Input>
          </FormItem>
          <FormItem :label="`${$t('maintenance.EquipmentType')}:`" class="item" prop="categoryId">
            <Select
                    v-model="formInline.categoryId "
                    filterable
                    clearable
                    :placeholder="`${$t('common.selectInfo')}`"
                    @on-change="handleChangeDevice"
            >
              <Option
                      v-for="(item) of category"
                      :value="item.value"
                      :key="item.value"
              >{{ item.label }}</Option>
            </Select>
          </FormItem>
          <!--          <FormItem label="保养位置" class="item" required>-->
          <!--            <Select-->
          <!--              v-model="formInline.classification"-->
          <!--              filterable-->
          <!--              clearable-->
          <!--              :placeholder="`${$t('common.inputInfo')}`"-->
          <!--            >-->
          <!--              <Option-->
          <!--                v-for="(item, index) of classification"-->
          <!--                :value="item.key"-->
          <!--                :key="index"-->
          <!--                >{{ item.name }}</Option-->
          <!--              >-->
          <!--            </Select>-->
          <!--          </FormItem>-->
          <!--          <FormItem label="保养分类" class="item" required>-->
          <!--            <Select-->
          <!--              v-model="formInline.position"-->
          <!--              filterable-->
          <!--              clearable-->
          <!--              :placeholder="`${$t('common.selectInfo')}`"-->
          <!--            >-->
          <!--              <Option-->
          <!--                v-for="(item, index) of position"-->
          <!--                :value="item.key"-->
          <!--                :key="index"-->
          <!--                >{{ item.name }}</Option-->
          <!--              >-->
          <!--            </Select>-->
          <!--          </FormItem>-->
        </div>
      </Form>
      <div class="addDev" @click="addDev">
        <Icon type="md-add-circle" size="20" />添加检测设备
      </div>
      <!--      <Form :label-width="100" class="search-form">-->
      <!--        <div class="label">-->
      <!--          <FormItem label="所属工厂" class="item">-->
      <!--            <Select-->
      <!--              v-model="formInline.category"-->
      <!--              filterable-->
      <!--              clearable-->
      <!--              :placeholder="`${$t('common.selectInfo')}`"-->
      <!--            >-->
      <!--              <Option-->
      <!--                v-for="(item, index) of category"-->
      <!--                :value="item.key"-->
      <!--                :key="index"-->
      <!--                >{{ item.name }}</Option-->
      <!--              >-->
      <!--            </Select>-->
      <!--          </FormItem>-->
      <!--          <FormItem label="生产线描述" class="item">-->
      <!--            <Select-->
      <!--              v-model="formInline.position"-->
      <!--              filterable-->
      <!--              clearable-->
      <!--              :placeholder="`${$t('common.selectInfo')}`"-->
      <!--            >-->
      <!--              <Option-->
      <!--                v-for="(item, index) of position"-->
      <!--                :value="item.key"-->
      <!--                :key="index"-->
      <!--                >{{ item.name }}</Option-->
      <!--              >-->
      <!--            </Select>-->
      <!--          </FormItem>-->
      <!--          <FormItem label="制造商" class="item">-->
      <!--            <Select-->
      <!--              v-model="formInline.classification"-->
      <!--              filterable-->
      <!--              clearable-->
      <!--              :placeholder="`${$t('common.inputInfo')}`"-->
      <!--            >-->
      <!--              <Option-->
      <!--                v-for="(item, index) of classification"-->
      <!--                :value="item.key"-->
      <!--                :key="index"-->
      <!--                >{{ item.name }}</Option-->
      <!--              >-->
      <!--            </Select>-->
      <!--          </FormItem>-->
      <!--           <FormItem :label="`${$t('ledger.EquipmentType')}:`" class="item">-->
      <!--            <Input-->
      <!--              type="text"-->
      <!--              v-model="text"-->
      <!--              :placeholder="`${$t('common.inputInfo')}`"-->
      <!--              class="inputBorder"-->
      <!--              :maxlength="32"-->
      <!--            ></Input>-->
      <!--          </FormItem>-->
      <!--          <FormItem label="" class="item">-->
      <!--            <Button type="primary">{{$t('common.Query')}}</Button>-->
      <!--          </FormItem>-->
      <!--        </div>-->
      <!--      </Form>-->
      <div class="tableContent">
        <Table ref="selection" :columns="columns" :data="data">
          <template slot-scope="{ row }" slot="action">
            <span class="operationBtn" @click="deleteDevRow(row)">{{$t('common.Delete')}}</span>
          </template>
        </Table>
        <!--        <div class="pageWrap">-->
        <!--          <Page-->
        <!--            :total="pageParams.total"-->
        <!--            :page-size="pageParams.pageSize"-->
        <!--            :page-size-opts="pageParams.pageSizeOption"-->
        <!--            :current="pageParams.pageNum"-->
        <!--            @on-change="changePageNum"-->
        <!--            @on-page-size-change="changePageSize"-->
        <!--            show-sizer-->
        <!--            show-total-->
        <!--            -->
        <!--          />-->
        <!--        </div>-->
      </div>
      <Modal :mask-closable="false"
              v-model="addDevVisible"
              :title="`${$t('ledger.NewDevice')}`"
              class="addDevModal"
              width="1400"
      >
        <Form :label-width="100" class="search-form">
          <div class="label">
            <FormItem label="所属工厂" class="item">
              <Select
                      v-model="searchParams.belongCompanyId"
                      filterable
                      clearable
                      :placeholder="`${$t('common.selectInfo')}`"
              >
                <Option
                        v-for="(item) of companyList"
                        :value="item.id"
                        :key="item.id"
                >{{ item.name }}</Option
                >
              </Select>
            </FormItem>
            <FormItem label="功能位置" class="item">
              <Cascader clearable :data="orgList" v-model="searchParams.orgId" :placeholder="`${$t('common.selectInfo')}`" change-on-select></Cascader>
            </FormItem>
            <FormItem :label="`${$t('maintenance.EquipmentNo')}:`" class="item">
              <Input
                      type="text"
                      v-model="searchParams.deviceMId"
                      :placeholder="`${$t('common.inputInfo')}`"
                      class="inputBorder"
                      :maxlength="32"
              ></Input>
            </FormItem>
            <FormItem :label="`${$t('common.machineno')}:`" class="item">
              <Input
                      type="text"
                      v-model="searchParams.deviceNo"
                      :placeholder="`${$t('common.inputInfo')}`"
                      class="inputBorder"
                      :maxlength="32"
              ></Input>
            </FormItem>
            <FormItem label="生产线描述" class="item">
              <Input v-model="searchParams.productionLine" clearable :placeholder="`${$t('common.inputInfo')}`"/>
              <!--              <Select-->
              <!--                v-model="formInline.position"-->
              <!--                filterable-->
              <!--                clearable-->
              <!--                :placeholder="`${$t('common.selectInfo')}`"-->
              <!--              >-->
              <!--                <Option-->
              <!--                  v-for="(item, index) of position"-->
              <!--                  :value="item.key"-->
              <!--                  :key="index"-->
              <!--                  >{{ item.name }}</Option-->
              <!--                >-->
              <!--              </Select>-->
            </FormItem>
<!--            <FormItem label="制造商" class="item">-->
<!--              <Input v-model="searchParams.manufacturer" clearable placeholder="请输入制造商"/>-->
              <!--              <Select-->
              <!--                v-model="formInline.classification"-->
              <!--                filterable-->
              <!--                clearable-->
              <!--                :placeholder="`${$t('common.inputInfo')}`"-->
              <!--              >-->
              <!--                <Option-->
              <!--                  v-for="(item, index) of classification"-->
              <!--                  :value="item.key"-->
              <!--                  :key="index"-->
              <!--                  >{{ item.name }}</Option-->
              <!--                >-->
              <!--              </Select>-->
<!--            </FormItem>-->
             <FormItem :label="`${$t('ledger.EquipmentType')}:`" class="item">
              <Input
                      type="text"
                      v-model="searchParams.specification"
                      :placeholder="`${$t('common.inputInfo')}`"
                      class="inputBorder"
                      :maxlength="32"
              ></Input>
            </FormItem>
            <FormItem label="" class="item">
              <Button type="primary" @click="changeNum">{{$t('common.Query')}}</Button>
            </FormItem>
          </div>
        </Form>
        <div>
          <Table ref="devSelection" :columns="addDevcolumns" :data="addDevdata"  @on-selection-change="handleSelectionChange"></Table>
          <div class="pageWrap">
            <Page
                    :total="addDevpageParams.total"
                    :page-size="addDevpageParams.pageSize"
                    :page-size-opts="$variable.pageSizes"
                    :current="addDevpageParams.pageNum"
                    @on-change="changePageNum"
                    @on-page-size-change="changePageSize"
                    show-sizer
                    show-total

            />
          </div>
        </div>
        <div slot="footer">
          <Button type="default" @click="addDevCancel">{{$t('common.Cancle')}}</Button>
          <Button type="primary" @click="addDevOk">{{$t('maintenance.Confirmed')}}</Button>
        </div>
      </Modal>
    </div>
    <!-- 第二步 -->
    <div v-if="current === 2" class="second">
      <Form
              class="search-form"
              ref="stepTwoValidate"
              :rules="ruleValidate"
              :model="stepTwoValidate"
      >
        <FormItem label="检测方式" class="item" prop="acctestType">
          <Select
                  v-model="stepTwoValidate.acctestType"
                  filterable
                  clearable
                  :placeholder="`${$t('common.selectInfo')}`"
                  disabled

          >
            <Option :value="item.key" v-for="item in cycle" :key="item.key">{{ item.name }}</Option>
          </Select>
        </FormItem>
        <FormItem :label="`${$t('maintenance.TriggerInterval')}:`" class="item">
<!--          <RadioGroup v-model="stepTwoValidate.intervalRate">-->
<!--            <Radio v-for="item in weeks" :key="item.id" :label="item.id">{{ item.name }}</Radio>-->
<!--          </RadioGroup>-->
          <Row v-if="stepTwoValidate.acctestType == 1">
            <Col span="16">
              <FormItem prop="intervalRate">
                <InputNumber :disabled="editId ? true : false" :min="0" :formatter="value => `${parseInt(value)}`" style="width: 100%" v-model="stepTwoValidate.intervalRate"></InputNumber>
              </FormItem>
            </Col>
            <Col span="8">
              <FormItem prop="triggerCycle">
                <Select
                        v-model="stepTwoValidate.triggerCycle"
                        filterable
                        clearable
                        :placeholder="`${$t('common.selectInfo')}`"
                        :disabled="editId ? true : false"
                >
                  <Option v-for="item in weeks" :key="item.key" :value="item.key">{{ item.name }}</Option>
                </Select>
              </FormItem>
            </Col>
          </Row>
<!--          <Row v-else-if="stepTwoValidate.acctestType == 2">-->
<!--            <Col span="16">-->
<!--              <FormItem prop="intervalRate">-->
<!--                <InputNumber :min="0" :formatter="value => `${parseInt(value)}`" style="width: 100%" v-model="stepTwoValidate.intervalRate"></InputNumber>-->
<!--              </FormItem>-->
<!--            </Col>-->
<!--            <Col span="8">-->
<!--              次-->
<!--            </Col>-->
<!--          </Row>-->
<!--          <Row v-else>-->
<!--            <Col span="16">-->
<!--              <FormItem prop="intervalRate">-->
<!--                <InputNumber :min="0" :formatter="value => `${parseInt(value)}`" style="width: 100%" v-model="stepTwoValidate.intervalRate"></InputNumber>-->
<!--              </FormItem>-->
<!--            </Col>-->
<!--            <Col span="8">-->
<!--              小时-->
<!--            </Col>-->
<!--          </Row>-->
        </FormItem>
        <FormItem :label="`${$t('maintenance.createTime')}:`" class="item" prop="firstTime">
<!--          disabledHours: getDisabledHours-->
          <DatePicker type="datetime" :options="options" :time-picker-options="{steps: [1, 60, 60]}" :placeholder="`${$t('common.selectInfo')}`" v-model="stepTwoValidate.firstTime"></DatePicker>
        </FormItem>
        <FormItem :label="`${$t('maintenance.planEndTime')}:`" class="item" prop="planEndTime">
          <DatePicker type="datetime" :options="options1" :time-picker-options="{steps: [1, 60, 60]}" :placeholder="`${$t('common.selectInfo')}`" v-model="stepTwoValidate.planEndTime"></DatePicker>
        </FormItem>
        <FormItem label="标准工时(min)" class="item">
          <InputNumber style="width: 100%" v-model="stepTwoValidate.itemHour" disabled></InputNumber>
        </FormItem>
        <FormItem :label="`${$t('maintenance.Taskduration')}:`" class="item" required>
          <Row>
            <Col span="10">
              <FormItem>
                <InputNumber :min="0" :formatter="value => `${parseInt(value)}`" style="width: 100%" v-model="stepTwoValidate.day"></InputNumber>
              </FormItem>
            </Col>
            <Col span="1">天</Col>
            <Col span="10">
              <FormItem>
                <InputNumber :min="0" :formatter="value => `${parseInt(value)}`" style="width: 100%" v-model="stepTwoValidate.hour"></InputNumber>
              </FormItem>
            </Col>
            <Col span="3">小时</Col>
          </Row>
        </FormItem>
      </Form>
    </div>
    <div v-if="current === 1" class="third">
      <div class="addPlan" @click="addPlan">
        <Icon type="md-add-circle" size="20" />添加检测内容
      </div>
      <div class="tableContent">
        <Table ref="selection" :columns="contentColumns" :data="contentData">
          <template slot-scope="{ row }" slot="action">
            <span class="operationBtn" @click="seeDetail(row)" >{{$t('common.CheckDetial')}}</span>
            <span class="operationBtn" @click="deleteRow(row)" style="paddingLeft: 10px">{{$t('common.Delete')}}</span>
          </template>
        </Table>
      </div>
      <Modal :mask-closable="false"
              v-model="visible"
              title="检测内容详情"
              class="checkContentModal"
              width='1200'
              footer-hide
      >
        <contentDetail :planMaterialList="materialList" :planToolList="toolList"></contentDetail>
      </Modal>
    </div>
    <div class="nextBtn">
      <Button @click="previous" v-if="current !== 0">{{$t('common.Pre')}}</Button>
      <Button type="primary" @click="next" v-if="current !== 2">{{$t('common.Next')}}</Button>
      <Button type="primary" :loading="loading" @click="create" v-if="current === 2">{{$t('common.Creatingsuccessful')}}</Button>
    </div>
    <Drawer title="添加检测内容" :styles="styles" :scrollable="true" v-model="drawerVisible" width="1200" class="drawer">
      <div class="search">
        <label>检测周期：</label>
        <Select
                v-model="searchPlanParams.triggerCycle"
                filterable
                clearable
                :placeholder="`${$t('common.inputInfo')}`"
                style="width:200px"
        >
          <Option
                  v-for="(item, index) of weeks"
                  :value="item.key"
                  :key="item.key"
          >{{ item.name }}</Option>
        </Select>
        <label>检测分类：</label>
        <Select
                v-model="searchPlanParams.classifyId"
                filterable
                clearable
                :placeholder="`${$t('common.inputInfo')}`"
                style="width:200px"
        >
          <Option
                  v-for="(item, index) of classification"
                  :value="item.value"
                  :key="item.value"
          >{{ item.label }}</Option>
        </Select>
        <label>检测位置：</label>
        <Select
                v-model="searchPlanParams.positionId"
                filterable
                clearable
                :placeholder="`${$t('common.selectInfo')}`"
                style="width:200px"
        >
          <Option
                  v-for="(item, index) of position"
                  :value="item.value"
                  :key="item.value"
          >{{ item.label }}</Option>
        </Select>
        <label>检测项目：</label>
        <Input
                v-model="searchPlanParams.itemProject"
                clearable
                style="width:200px"/>
        <Button type="primary" @click="changePlanNum">{{$t('common.Query')}}</Button>
      </div>
      <div style="margin: 10px">
        <Table ref="drawerSelection" :columns="drawerColumns" :data="drawerData" @on-selection-change="handleDrawerChange"></Table>
      </div>
      <div class="demo-drawer-footer">
        <Button style="margin-right: 8px" @click="handleDrawerCancel">{{$t('common.Cancle')}}</Button>
        <Button type="primary" @click="handleDrawerOk">{{$t('maintenance.Confirmed')}}</Button>
      </div>
    </Drawer>
  </div>
</template>

<script>
  import recursion from '../../../../../util/recursion'
import contentDetail from './contentDetail.vue'
export default {
  name: "addSpotCheckPlan",
  components: {
    contentDetail
  },
  props: ['mainDevice', 'factoryList', 'planPositionList', 'planClassifyList', 'editId'],
  data() {
    return {
      current: 0,
      visible: false,
      drawerVisible: false,
      loading: false,
      addDevVisible: false,
      searchParams: {},
      searchPlanParams: {},
      options: {
        // disabledDate (date) {
        //   return date && date.valueOf() < Date.now() - 86400000;
        // }
      },
      options1: {
        disabledDate: (date) => {
          let data = this.stepTwoValidate.firstTime ? this.stepTwoValidate.firstTime : ''
          return date && date.valueOf() <= new Date(data).valueOf();
        }
      },
      styles: {
        height: 'calc(100% - 55px)',
        overflow: 'scroll',
        paddingBottom: '53px',
        position: 'static'
      },
      formInline: {
        categoryId: '',
        planName: '',
      },
      stepOneRuleValidate: {
        categoryId: [
          { required: true, message: "请选择设备类别", trigger: "change" },
        ],
        planName: [
          { required: true, message: "请输入检测计划（设备类别_保养周期）", trigger: "blur" },
        ],
      },
      stepTwoValidate: {
        acctestType: '1',
        intervalRate: null,
        triggerCycle: '',
        day: null,
        hour: null,
        firstTime: this.$moment(new Date()).format('YYYY-MM-DD HH:00:00'),
        planEndTime: this.$moment(new Date()).format('YYYY-MM-DD HH:00:00')
      },
      ruleValidate: {
        acctestType: [
          { required: true, message: "请输入检测方式", trigger: "change" },
        ],
        intervalRate: [
          { required: true, type: 'number', message: "请输入触发周期", trigger: "blur" },
        ],
        triggerCycle: [
          { required: true, message: "请选择周期", trigger: "change" },
        ],
        firstTime: [
          { required: true,  message: "请选择日期" },
        ],
        planEndTime: [
          { required: true, message: "请选择日期" },
        ],
        day: [
          { required: true, type: 'number', message: "请输入天数", trigger: "blur" },
        ],
        hour: [
          { required: true, type: 'number', message: "请输入小时", trigger: "blur" },
        ],
      },
      columns: [
        // { type: "selection", width: 60, align: "center" },
        { title: `${ this.$t('common.Belongsfactory') }`, key: "belongCompanyName" },
        { title: `${ this.$t('maintenance.EquipmentNo') }`, key: "deviceMId" },
        {  title: `${ this.$t('common.machineno') }`, key: "deviceNo" },
        { title: `${ this.$t('maintenance.EquipmentName') }`, key: "deviceName" },
        { title: `${ this.$t('ledger.EquipmentType') }`, key: "specification" },
        { title: `${ this.$t('fault.FunctionalLocation') }`, key: "orgName" },
        { title: `${ this.$t('common.Productioncode') }`, key: "productionCode" },
        { title: `${ this.$t('common.ProductionDescription') }`, key: "productionLine" },
        { title: `${ this.$t('common.operation') }`, slot: "action", width: 150, align: "center" },
      ],
      addDevcolumns: [
        { type: "selection", width: 60, align: "center" },
        { title: `${ this.$t('common.Belongsfactory') }`, key: "belongCompanyName" },
        { title: `${ this.$t('maintenance.EquipmentNo') }`, key: "deviceMId" },
        {  title: `${ this.$t('common.machineno') }`, key: "deviceNo" },
        { title: `${ this.$t('maintenance.EquipmentName') }`, key: "deviceName" },
        { title: `${ this.$t('ledger.EquipmentType') }`, key: "specification" },
        { title: `${ this.$t('fault.FunctionalLocation') }`, key: "orgName" },
        { title: `${ this.$t('common.Productioncode') }`, key: "productionCode" },
        { title: `${ this.$t('common.ProductionDescription') }`, key: "productionLine" },
      ],
      addDevdata: [],
      data: [],
      materialList: [],
      toolList: [],
      drawerSelectionData: [],
      category: this.mainDevice,
      companyList: this.factoryList,
      position: this.planPositionList,
      classification: this.planClassifyList,
      cycle: [
        {name: '定期检测', key: '1'},
        // {name: '计数', key: '2'},
        // {name: '计时', key: '3'},
      ],
      weeks: [
        {name: '日', key: '1'},
        {name: '周', key: '2'},
        {name: '月', key: '3'},
        {name: '季度', key: '4'},
        {name: '半年度', key: '5'},
        {name: '年度', key: '6'},
        // {name: '计数', key: '7'},
        // {name: '计时', key: '8'}
      ],
      pageParams: {
        total: 64,
        pageSize: 10,
        pageNum: 1,
        pageSizeOption: [10, 20, 30, 40],
      },
      addDevpageParams: {
        total: 0,
        pageSize: 50,
        pageNum: 1,
        pageSizeOption: [50, 100, 150, 200],
      },
      contentColumns: [
        { title: `${ this.$t('common.testitems') }`, key: 'item_project'},
        {title: `${ this.$t('common.testmethod') }`, key: 'item_method'},
        { title: `${ this.$t('maintenance.workinghours') }`, key: 'item_hours'},
        { title: `${ this.$t('maintenance.Unit') }`, key: 'unit_name'},
        {title: `${ this.$t('maintenance.UpperLimit') }`, key: 'max_value'},
        { title: `${ this.$t('maintenance.LowerLimit') }`, key: 'min_value'},
        {title: `${ this.$t('common.operation') }`, slot: 'action', width: 200, align: 'center'},
      ],
      contentData: [],
      drawerColumns: [
        { type: "selection", width: 60, align: "center" },
        {title: '检测分类', key: 'item_classify',align: 'center',minWidth: 100, tooltip: true},
        {title: '检测位置', key: 'item_position',align: 'center',minWidth: 100, tooltip: true},
        { title: `${ this.$t('common.testitems') }`, key: 'item_project',align: 'center',minWidth: 100, tooltip: true},
        {title: `${ this.$t('common.testmethod') }`, key: 'item_method',align: 'center',minWidth: 100, tooltip: true},
        { title: `${ this.$t('maintenance.workinghours') }`, key: 'item_hours',align: 'center',minWidth: 120, },
        { title: `${ this.$t('maintenance.Unit') }`, key: 'unit_name',align: 'center',minWidth: 100, },
        {title: `${ this.$t('maintenance.UpperLimit') }`, key: 'max_value',align: 'center',minWidth: 100, },
        { title: `${ this.$t('maintenance.LowerLimit') }`, key: 'min_value',align: 'center',minWidth: 100, },
      ],
      drawerData: [],
      orgList: []
    };
  },
  watch: {
    mainDevice(newValue) {
      console.log(newValue)
    }
  },
  created() {
    console.log(this.editId)
    if (this.editId) {
      this.getPlanDetail(this.editId)
    }
    this.getOrgList()
  },
  // computed: {
  //   getDisabledHours() {
  //     let arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
  //     let hours = new Date().getHours()
  //     // let newHours = new Date(this.stepTwoValidate.firstTime).getHours()
  //     let disabledHours = arr.filter(item => item < hours)
  //     return disabledHours
  //   }
  //
  // },
  mounted() {},
  methods: {
    back() {
      this.$emit("handlePlanOk");
    },
    getOrgList() {
      this.axios({
        method: 'get',
        url: '/basic/organization/findListByToken',
        params: {}
      }).then(res => {
        if(res.code === 200){
          const obj ={
            label: 'name',
            value: 'code',
            children: 'children'
          }
          this.orgList = recursion.convertTree(res.data, obj)
        }else{
          this.$Message.warning(({content:res.msg,duration:6,closable:true}));
        }
      })
    },
    getPlanDetail(id) {
      this.axios({
        method: 'get',
        url: '/dms/dcmAcctestPlan/queryById',
        params: {
          id
        }
      }).then(res => {
        if(res.code === 200){
          
          this.formInline = {
            planName: res.data.planName,
            categoryId: res.data.categoryId ? res.data.categoryId.toString() : ''
          }
          this.stepTwoValidate = {
            ...res.data,
            day: res.data.pdays,
            hour: res.data.phours,
            acctestType: res.data.acctestType ? res.data.acctestType.toString() : '',
            // intervalRate: res.data.intervalRate ? res.data.intervalRate.toString() : '',
            triggerCycle: res.data.triggerCycle ? res.data.triggerCycle.toString() : ''
          }
          this.data = res.data.dcmAcctestDetailList
          this.contentData = res.data.dcmAcctestProjectList.map(item => {
            return {
              ...item,
              item_project: item.itemProject,
              item_method: item.itemMethod,
              item_hours: item.itemHours,
              unit_name: item.unitName,
              max_value: item.maxValue,
              min_value: item.minValue,
            }
          })
          // this.effDetail = res.data
        }else{
          this.$Message.warning(({content:res.msg,duration:6,closable:true}));
        }
      })
    },
    changePageSize(pageSize) {
      this.addDevpageParams.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val){
      this.addDevpageParams.pageNum = val;
      this.searchList();
    },
    next() {
      if (this.current == 0) {
        this.$refs["stepOneValidate"].validate((valid) => {
          if (valid) {
            if(!this.data.length) {
              this.$Message.warning(({content: '请添加检测设备！', duration: 6, closable: true}));
              return false
            }
            if (!this.editId) {
              this.axios({
                method: 'get',
                url: '/dms/dcmAcctestPlan/validPlanName',
                params: {
                  planName : this.formInline.planName
                }
              }).then(res => {
                if (res.code == 200) {
                  this.current += 1;
                }else {
                  this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
              })
            }else {
              this.axios({
                method: 'get',
                url: '/dms/dcmAcctestPlan/validPlanName',
                params: {
                  id: this.editId,
                  planName : this.formInline.planName
                }
              }).then(res => {
                if (res.code == 200) {
                  this.current += 1;
                }else {
                  this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
              })
            }
            // this.$Message.success('Success!');
          } else {
            // this.$Message.warning(({content: '请将信息填写完整！', duration: 6, closable: true}));
            return;
          }
        });
      } else if (this.current == 1) {
        if(!this.contentData.length) {
          this.$Message.warning(({content: '请添加检测内容！', duration: 6, closable: true}));
          return false
        }
        let hour = this.contentData.filter(item => item.item_hours).reduce((pre, current) => pre + current.item_hours ,0)
        console.log(hour)
        this.stepTwoValidate.itemHour = hour
        this.current += 1;
      }else {
        this.current += 1;
      }
    },
    previous() {
      this.current -= 1;
    },
    create() {
      this.$refs["stepTwoValidate"].validate((valid) => {
        if (valid) {
          let timeStamp = new Date(this.stepTwoValidate.planEndTime).getTime() - new Date(this.stepTwoValidate.firstTime).getTime()
          let hour =  parseInt(parseInt(timeStamp) / parseInt(1000 * 3600))
          let tempDay = this.stepTwoValidate.day ? this.stepTwoValidate.day : 0
          let tempHour = this.stepTwoValidate.hour ? this.stepTwoValidate.hour : 0
          let aliveHour = parseInt(tempDay * 24) + parseInt(tempHour)
          let itemHour = Number(this.stepTwoValidate.itemHour)/60

          if(!this.stepTwoValidate.day && !this.stepTwoValidate.hour) {
            this.$Message.warning(({content: '请任意输入任务存活时间的天数或者小时！', duration: 6, closable: true}));
            return false
          }
          if(new Date(this.stepTwoValidate.firstTime).getTime() >= new Date(this.stepTwoValidate.planEndTime).getTime()) {
            this.$Message.warning(({content: '首次生成时间不得大于计划截止时间！', duration: 6, closable: true}));
            return false
          }
          if (hour <= aliveHour) {
            this.$Message.warning(({content: '计划截止时间与首次生成时间之差需超过任务存活时间！', duration: 6, closable: true}));
            return false
          }
          if (itemHour >= aliveHour) {
            this.$Message.warning(({content: '任务存活时间需超过标准工时！', duration: 6, closable: true}));
            return false
          }
          this.loading = true
          let firstTime = this.$moment(this.stepTwoValidate.firstTime).format('YYYY-MM-DD HH:00:00')
          let planEndTime = this.$moment(this.stepTwoValidate.planEndTime).format('YYYY-MM-DD HH:00:00')
          // let effectiveHour = this.stepTwoValidate.day * 24 + this.stepTwoValidate.hour
          // let triggerCycle = this.stepTwoValidate.checkingType ==1 ? this.stepTwoValidate.triggerCycle : this.stepTwoValidate.checkingType ==2 ? 7 : 8

          let dcmAcctestDetailList = this.data.map(item => {
            return {
              belongCompanyId: item.belongCompanyId,
              deviceMId: item.deviceMId,
              orgId: item.orgId,
              useCompanyId: item.useCompanyId
            }
          })
          let dcmAcctestProjectList = this.contentData.map(item => {
            return {
              itemId: item.itemId,
              itemMethod: item.item_method,
              itemProject: item.item_project,
              maxValue: item.max_value,
              minValue: item.min_value,
              unitName: item.unit_name,
              itemHours: item.item_hours
            }
          })
          let data = {
            planName: this.formInline.planName,
            categoryId: this.formInline.categoryId,
            acctestType: this.stepTwoValidate.acctestType,
            intervalRate: this.stepTwoValidate.intervalRate,
            triggerCycle: this.stepTwoValidate.triggerCycle,
            pdays: this.stepTwoValidate.day,
            phours: this.stepTwoValidate.hour,
            firstTime,
            planEndTime,
            dcmAcctestDetailList,
            dcmAcctestProjectList
          }
          console.log(data)
          if (!this.editId) {
            this.axios({
              method: 'post',
              url: '/dms/dcmAcctestPlan/add',
              data
            }).then(res => {
              
              if(res.code === 200){
                this.$emit('handlePlanOk')
                this.$Message.success(({content:'新增检测计划成功！',duration:2,closable:true}))
              }else{
                this.$Message.warning(({content:res.msg,duration:6,closable:true}));
              }
            }).finally(() => {
              this.loading = false
            })
          }else {
            let params = {
              ...data,
              id: this.editId
            }
            this.axios({
              method: 'put',
              url: '/dms/dcmAcctestPlan/edit',
              data: params
            }).then(res => {
              
              if(res.code === 200){
                this.$emit('handlePlanOk')
                this.$Message.success(({content:'编辑检测计划成功！',duration:2,closable:true}))
              }else{
                this.$Message.warning(({content:res.msg,duration:6,closable:true}));
              }
            }).finally(() => {
              this.loading = false
            })
          }
        } else {
          return;
        }
      });


    },
    addDev() {
      if(!this.formInline.categoryId) {
        this.$Message.warning(({content:'请选择设备类别！',duration:6,closable:true}))
        return false
      }
      this.addDevVisible = true;
      this.searchParams = {}
      this.searchList()
    },
    handleSelectionChange(selectionData) {
      console.log(selectionData)
      let arr = [...selectionData]
      this.selectData = arr
    },
    addDevCancel() {
      this.addDevVisible = false
      this.$refs.devSelection.selectAll(false)
    },
    addDevOk() {
      if (this.data.length) {
        let arr = this.data.filter(item => this.selectData.some(x => x.id == item.id))
        console.log(arr)
        if (arr.length) {
          this.$Message.warning(({content: '有重复数据，请重新选择！', duration: 6, closable: true}));
          return false
        }
        this.addDevVisible = false
        this.data = [...this.data, ...this.selectData]
        this.$refs.devSelection.selectAll(false)
      }else {
        this.addDevVisible = false
        this.data = [...this.data, ...this.selectData]
        this.$refs.devSelection.selectAll(false)
      }

    },
    handleChangeDevice(value) {
      console.log(value)
      // this.searchList()
    },
    //分页
    changeNum(){
      this.addDevpageParams.pageNum = 1;
      this.searchList();
    },
    searchList() {
      let deviceMIds = ''
      let params = {}
      console.log(this.data)
      this.data.map(item => {
        deviceMIds = item.deviceMId + ',' + deviceMIds
      })
      if (deviceMIds) {
        params = {
          deviceMIds: deviceMIds.substr(0, deviceMIds.length-1),
          categoryId: this.formInline.categoryId,
          pageNo:this.addDevpageParams.pageNum,
          pageSize:this.addDevpageParams.pageSize,
        };
      }else {
        params = {
          categoryId: this.formInline.categoryId,
          pageNo:this.addDevpageParams.pageNum,
          pageSize:this.addDevpageParams.pageSize,
        };
      }

      for (let key in this.searchParams) {
        if (key === 'orgId' && this.searchParams['orgId']) {
          const arr = this.searchParams[key]
          const { length, last=length-1 } = arr
          this.$set(params, key, arr[last])
        }else {
          if (this.searchParams[key]) {
            this.$set(params, key, this.searchParams[key])
          }
        }

      }
      this.axios({
        method: 'get',
        url: '/dms/dcmAcctestPlan/queryDeviceByCategory',
        params
      }).then(res => {
        
        if(res.code === 200){
          this.addDevdata = res.data.list
          this.addDevpageParams.total = res.data.total
        }else{
          this.$Message.warning(({content:res.msg,duration:6,closable:true}));
        }
      })
    },
    changePlanNum() {
      this.searchPlanList();
    },
    searchPlanList() {
      let params = {
        // triggerCycle: this.stepTwoValidate.triggerCycle
        categoryId: this.formInline.categoryId,
        // pageNo:this.addDevpageParams.pageNum,
        // pageSize:this.addDevpageParams.pageSize,
      };
      for (let key in this.searchPlanParams) {
        if (key === 'orgId' && this.searchPlanParams['orgId']) {
          const arr = this.searchPlanParams[key]
          const { length, last=length-1 } = arr
          this.$set(params, key, arr[last])
        }else {
          if (this.searchPlanParams[key]) {
            this.$set(params, key, this.searchPlanParams[key])
          }
        }

      }
      this.axios({
        method: 'get',
        url: '/dms/dcmAcctestPlan/queryItemList',
        params
      }).then(res => {
        
        if(res.code === 200){
          this.drawerData = res.data
        }else{
          this.$Message.warning(({content:res.msg,duration:6,closable:true}));
        }
      })
    },
    handleDrawerChange(data) {
      let arr = []
      data.map(item => {
        arr.push(item)
      })
      this.drawerSelectionData = arr
    },
    addPlan() {
      this.searchPlanParams = {}
      this.drawerVisible = true
      this.searchPlanList()
    },
    handleDrawerCancel() {
      this.drawerVisible = false
      this.$refs.drawerSelection.selectAll(false)
    },
    handleDrawerOk() {
      if (this.contentData.length) {
        let arr = this.contentData.filter(item => this.drawerSelectionData.some(x => x.id == item.id))
        console.log(arr)
        if (arr.length) {
          this.$Message.warning(({content: '有重复数据，请重新选择！', duration: 6, closable: true}));
          return false
        }
        this.drawerVisible = false
        this.contentData = [...this.contentData, ...this.drawerSelectionData]
        this.$refs.drawerSelection.selectAll(false)
      }else {
        this.drawerVisible = false
        this.contentData = [...this.contentData, ...this.drawerSelectionData]
        this.$refs.drawerSelection.selectAll(false)
      }
    },
    seeDetail(row) {
      this.visible = true
      this.getWlDetail(row.itemId || row.id)
    },
    getWlDetail(itemId) {
      this.axios({
        method: 'get',
        url: '/dms/dcmAcctestTask/queryByItemId',
        params: {
          itemId,
        }
      }).then(res => {
        
        if(res.code === 200){
          this.materialList = res.data.materialList
          this.toolList = res.data.toolList
        }else{
          this.$Message.warning(({content:res.msg,duration:6,closable:true}));
        }
      })
    },
    deleteRow(row) {
      this.contentData = this.contentData.filter(item => item.id != row.id)
    },
    deleteDevRow(row) {
      this.data = this.data.filter(item => item.id != row.id)
    },
  },
};
</script>

<style lang="scss">
  .addMaintainPlan {
    background: #fff;
    .title {
      display: flex;
      justify-content: flex-start;
      font-size: 20px;
      padding: 10px;
      border-bottom: 1px solid #dddddd;
      align-items: center;
      .back {
        color: #187bdb;
        font-size: 16px;
        padding-left: 20px;
        cursor: pointer;
      }
      .steps {
        width: 400px;
        margin-left: auto;
      }
    }
    .searchBox {
      .addDev {
        font-size: 16px;
        padding: 20px 0 0 10px;
      }
      .labelTop {
        display: flex;
        /*justify-content: space-between;*/
        border-bottom: 2px solid #d7d7d7;
        .item {
          width: 25%;
        }
      }
      .label {
        display: flex;
        .item {
          margin-left: 10px;
        }
      }
    }
    .nextBtn {
      text-align: center;
      padding: 50px 0px;
      button {
        margin: 10px;
      }
    }
  }
  .second {
    .search-form {
      width: 30%;
    }
  }
  .third {
    .addPlan {
      font-size: 16px;
      padding: 20px 0 0 10px;
    }
  }
  .addDevModal {
    .search-form {
      .label {
        display: flex;
      }
    }
  }
  .drawer {
    .search {
      display: flex;
      align-items: center;
      button {
        margin-left: 10px;
      }
    }
    .demo-drawer-footer{
      width: 100%;
      position: absolute;
      bottom: 0;
      left: 0;
      padding: 0 30px 15px 30px;
      text-align: right;
      background: #fff;
    }
  }
</style>
